const Koa = require('koa');
const Router = require('koa-router');
const mockList = require('./mock/index');


const app = new Koa();
const router = new Router();

async function getRes(fn,ctx) {
  return new Promise(resolve =>{
    setTimeout(()=>{
      const res =fn(ctx)
      resolve(res)
    },1000)
  })
}


//注册mock路由
mockList.forEach(e => {
  const {url,method,response} = e;
  router[method](url, async (ctx) => {
    const res = await getRes(response,ctx)
    // 获得结果后返回
    ctx.body = res
  });
});

//允许跨域
app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  ctx.set('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  if (ctx.method === 'OPTIONS') {
    ctx.status = 204;
    return;
  }
  await next();
});

//注册路由
app.use(router.routes()); 
app.listen(3001);